args = commandArgs;
source("scripts2/sim.R");
#args = "list/stock_ss.csv"
hold_list_src = "hold_list.txt"
hold_list = read.csv(hold_list_src, head=T, colClasses=c("character", "character", "character", "Date"));
stock_list = read.csv(args, colClasses="character", head=F);

hold_list_insert_index = length(hold_list$Name) + 1;
today = as.character(Sys.Date());
Debug = F;
for (stock_name in stock_list$V1) {
    try ({    
    profit = c();
    stock = getSymbols(stock_name, auto.assign=F);
    stock_close = stock[,4];
    stock_vol = stock[,5];
    total_length = length(stock_close);

    stock_macd2 = MACD(stock_close, 10, 30, 13);
    stock_macd = MACD(stock_close, 7, 40, 7);

    stock_macd_diff = stock_macd[,1] - stock_macd[,2];
    stock_bband = BBands(stock_close, 20);
    stock_SMA30 = SMA(stock_close, 30)
    recur = total_length;
    final_price = stock_close[total_length];
    init_price = stock_close[recur-2];
    class(final_price) <- "numeric";
    class(init_price) <- "numeric";
    orig_gain = (final_price - init_price) / final_price;
    buy_stock = F;
    buy_stock = buy(Debug, recur, stock_close, stock_macd2[,1], stock_macd2[,2], stock_macd_diff); 
             
    if (
        buy_stock == T   
        #orig_gain <= -0.15      
    ) {
        # Hit : Buy Signal
        # Start to look up sell position
        if ( !(stock_name %in% hold_list$Name) ) {
            print( paste(stock_name, ", buy at price", stock_close[recur]) );
                        
            hold_list[hold_list_insert_index, ] = c(stock_name, stock_close[recur], 0, today);
            hold_list_insert_index = hold_list_insert_index + 1;
        }
    }
    
    latest_vol = stock_vol[recur];
    latest_vol_1 = stock_vol[recur-1];
    class(latest_vol) <- "numeric";
    class(latest_vol_1) <- "numeric";
    if (latest_vol > latest_vol_1 * 4) {
        print( paste(stock_name, ", big vol!!") );  
    }

    }) # End of Try

} # End of Symbol Scan
write.csv(hold_list, "hold_list.txt", row.names=F);

